#include "DynLibManager.h"
#include "../BoostForeach.h"
#include "../fuLogger.h"

BEGIN_NAMESPACE_CPPX

DynLibManager::~DynLibManager( void )
{
	// Unload & delete resources in turn
	foreach(DynLibMap::value_type & value,m_DynLibs){
		delete value.second;
	}

	// Empty the list
	m_DynLibs.clear();
}

DynLib* DynLibManager::find_dynlib( const std::string &name )
{
	DynLibMap::iterator it = m_DynLibs.find(name);
	if(it != m_DynLibs.end())
		return it->second;
	return NULL;
}

DynLib* DynLibManager::load_dynlib( const std::string & filename )
{
	DynLib * pLib = find_dynlib(filename);
	if( pLib != NULL )
		return pLib;
	pLib = new DynLib(filename);
	if( !pLib->IsLoaded() ){
		delete pLib;
		return NULL;
	}
    std::string dll_name = pLib->getName();
	std::pair<DynLibMap::iterator,bool> result = m_DynLibs.insert(DynLibMap::value_type(dll_name,pLib));
	if(!result.second){
		//fuLoggerRef() << "DynLibManager : DynLib Already exist :" << pLib->getName() << fuEnter();
	}
    //fuLoggerRef() << "DynLibManager : DynLib " << pLib->getName() << " is loaded." << fuEnter();
	return pLib;
}

void DynLibManager::unload_dynlib( DynLib *& pLib )
{
	if(!pLib)
		return;
	m_DynLibs.erase(pLib->getName());
    //fuLoggerRef() << "DynLibManager : DynLib " << pLib->getName() << " is unloaded." << fuEnter();
	delete pLib;
	pLib = NULL;
}

END_NAMESPACE_CPPX
